package collector.core.util.httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	public static DefaultHttpClient newHttpClient() {
		return newHttpClient(null, null);
	}

	public static DefaultHttpClient newHttpClient(String charset, String userAgent) {
		if(charset == null) charset = "UTF-8";
		if(userAgent == null) userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; ko; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9 (.NET CLR 3.5.30729)";

		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, charset);
		HttpProtocolParams.setUserAgent(params, userAgent);
		HttpProtocolParams.setUseExpectContinue(params, true);

		DefaultHttpClient httpclient = new DefaultHttpClient(params);

		return httpclient;
	}

	public static String getHtml(DefaultHttpClient httpclient, String url)
	throws IOException {
		HttpGet httpget = new HttpGet(url);
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String responseBody = null;
		try {
			responseBody = httpclient.execute(httpget, responseHandler);
		} catch (ClientProtocolException e) {
			httpget.abort();
			throw e;
		}
		return responseBody;
	}

	public static String postHtml(DefaultHttpClient httpclient, String url, String[][] params)
	throws IOException {
		List<NameValuePair> nvps = HttpUtil.makeNameValuePair(params);
		HttpPost httpost = new HttpPost(url);
		String responseBody;
		try {
			httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
				responseBody = httpclient.execute(httpost, responseHandler);
		} catch (ClientProtocolException e) {
			httpost.abort();
			throw e;
		}

		return responseBody;
	}

	public static byte[] getHtmlBinary(DefaultHttpClient httpclient, String url)
	throws IOException {
		byte[] bytes = null;
		HttpGet httpget = new HttpGet(url);
		HttpResponse response;
		try {
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				bytes = EntityUtils.toByteArray(entity);
			}
		return bytes;
		} catch (ClientProtocolException e) {
			httpget.abort();
			throw e;
		}
	}
	
	public static List<NameValuePair> makeNameValuePair(String[][] params) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for(int i=0; i<params.length; i++) {
			nvps.add(new BasicNameValuePair(params[i][0], params[i][1]));
		}
		return nvps;
	}

	public static void printCookies(DefaultHttpClient httpClient) {
		StringBuilder strb = new StringBuilder();
		strb.append("COOKIES ================================\n");
		List<Cookie> cookies = httpClient.getCookieStore().getCookies();
		if (cookies.isEmpty()) {
			strb.append("None\n");
		} else {
			for (int i = 0; i < cookies.size(); i++) {
				strb.append("- " + cookies.get(i).toString() + "\n");
			}
		}
		System.out.println(strb.toString());
	}
	
	public static String encodeUrl(String str) {
		try {
			return URLEncoder.encode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}
	
	public static String decodeUrl(String str) {
		try {
			return URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
		}
		return null;
	}
	
	public static void sleep(int secs) {
		try {
			Thread.sleep(secs * 1000);
		} catch (InterruptedException e) {
		}
	}
}
